// utils/auth.js
import { userAPI } from './api.js'

const app = getApp()

// 登录状态管理
class AuthManager {
  constructor() {
    this.isLoggedIn = false
    this.userInfo = null
    this.token = null
    this.refreshToken = null
    this.isRefreshing = false
    this.refreshPromise = null
  }

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token')
    const refreshToken = wx.getStorageSync('refreshToken')
    const userInfo = wx.getStorageSync('userInfo')
    
    console.log('检查登录状态:', {
      hasToken: !!token,
      hasRefreshToken: !!refreshToken,
      hasUserInfo: !!userInfo
    })
    
    // 只要有token就认为登录有效
    if (token) {
      this.token = token
      this.refreshToken = refreshToken || token
      this.userInfo = userInfo
      this.isLoggedIn = true
      console.log('登录状态有效')
      return true
    }
    
    // 如果没有token，清除登录状态
    if (refreshToken || userInfo) {
      console.warn('没有token但有其他登录信息，清除登录状态')
      this.logout()
    }
    
    return false
  }

  // 微信登录
  wxLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (loginRes) => {
          resolve(loginRes.code)
        },
        fail: (error) => {
          console.error('微信登录失败:', error)
          reject(error)
        }
      })
    })
  }

  // 手机号登录
  phoneLogin(phoneCode) {
    return new Promise((resolve, reject) => {
      this.wxLogin().then(wxCode => {
        const loginData = {
          type: 'mini_app',
          code: wxCode,
          phoneCode: phoneCode
        }
        
        userAPI.login(loginData).then(result => {
          console.log('登录API返回结果:', result)
          
          const loginData = result.data
          
          // 保存登录信息
          if (loginData.token) {
            wx.setStorageSync('token', loginData.token)
            this.token = loginData.token
            console.log('保存token:', loginData.token)
          }
          
          if (loginData.refreshToken) {
            wx.setStorageSync('refreshToken', loginData.refreshToken)
            this.refreshToken = loginData.refreshToken
            console.log('保存refreshToken:', loginData.refreshToken)
          } else if (loginData.refresh_token) {
            wx.setStorageSync('refreshToken', loginData.refresh_token)
            this.refreshToken = loginData.refresh_token
            console.log('保存refreshToken (下划线格式):', loginData.refresh_token)
          } else {
            console.warn('登录响应中没有refreshToken，使用token作为refreshToken')
            wx.setStorageSync('refreshToken', loginData.token)
            this.refreshToken = loginData.token
            console.log('使用token作为refreshToken:', loginData.token)
          }
          
          // 立即设置登录状态
          this.isLoggedIn = true
          
          // 获取用户信息（可选）
          this.getUserProfile().then(() => {
            console.log('用户信息获取成功')
            resolve(result)
          }).catch(error => {
            console.error('获取用户信息失败，但不影响登录状态:', error)
            resolve(result)
          })
        }).catch(error => {
          console.error('登录失败:', error)
          reject(error)
        })
      }).catch(error => {
        console.error('微信登录失败:', error)
        reject(error)
      })
    })
  }

  // 获取用户信息
  getUserProfile() {
    console.log('获取用户信息')
    return new Promise((resolve, reject) => {
      userAPI.getUserProfile().then(userInfo => {
        wx.setStorageSync('userInfo', userInfo)
        this.userInfo = userInfo
        
        if (app && app.globalData) {
          app.globalData.userInfo = userInfo
        }
        
        resolve(userInfo)
      }).catch(error => {
        console.error('获取用户信息失败:', error)
        reject(error)
      })
    })
  }

  // 退出登录
  logout() {
    this.isLoggedIn = false
    this.userInfo = null
    this.token = null
    this.refreshToken = null
    this.isRefreshing = false
    this.refreshPromise = null
    
    wx.removeStorageSync('token')
    wx.removeStorageSync('refreshToken')
    wx.removeStorageSync('userInfo')
    
    if (app && app.globalData) {
      app.globalData.userInfo = null
      app.globalData.isLogin = false
    }
  }

  // 刷新token
  refreshAccessToken() {
    if (this.isRefreshing) {
      return this.refreshPromise
    }

    if (!wx.getStorageSync('refreshToken')) {
      console.warn('没有refreshToken，清除登录状态')
      this.logout()
      return Promise.reject(new Error('No refresh token available, please login again'))
    }

    this.isRefreshing = true
    this.refreshPromise = new Promise((resolve, reject) => {
      userAPI.refreshToken({
        refreshToken: wx.getStorageSync('refreshToken')
      }).then(result => {
        console.log('刷新tokenAPI返回结果:', result)
        
        const tokenData = result.data
        
        // 更新token
        if (tokenData.token) {
          wx.setStorageSync('token', tokenData.token)
          this.token = tokenData.token
          console.log('更新token:', tokenData.token)
        }

        if (tokenData.refreshToken) {
          wx.setStorageSync('refreshToken', tokenData.refreshToken)
          this.refreshToken = tokenData.refreshToken
          console.log('更新refreshToken:', tokenData.refreshToken)
        } else if (tokenData.refresh_token) {
          wx.setStorageSync('refreshToken', tokenData.refresh_token)
          this.refreshToken = tokenData.refresh_token
          console.log('更新refreshToken (下划线格式):', tokenData.refresh_token)
        }

        resolve(result)
      }).catch(error => {
        console.error('刷新token失败:', error)
        
        // 刷新失败，清除登录状态但保留refreshToken
        this.isLoggedIn = false
        this.userInfo = null
        this.token = null
        this.isRefreshing = false
        this.refreshPromise = null
        
        // 只清除token和userInfo，保留refreshToken用于后续重试
        wx.removeStorageSync('token')
        wx.removeStorageSync('userInfo')
        // 不清除refreshToken: wx.removeStorageSync('refreshToken')
        
        if (app && app.globalData) {
          app.globalData.userInfo = null
          app.globalData.isLogin = false
        }
        
        reject(error)
      }).finally(() => {
        this.isRefreshing = false
        this.refreshPromise = null
      })
    })

    return this.refreshPromise
  }

  // 获取当前token
  getToken() {
    return wx.getStorageSync('token')
  }

  // 获取当前refreshToken
  getRefreshToken() {
    return wx.getStorageSync('refreshToken')
  }

  // 显示登录弹窗（简化版，实际由页面处理）
  showLoginModal() {
    // 实际登录弹窗由各个页面自己处理
    console.log('需要显示登录弹窗')
  }
}

// 创建全局登录管理器实例
const authManager = new AuthManager()

export default authManager 